package cn.edu.hhu.teacher.dao;

import cn.edu.hhu.teacher.bean.Student;
import cn.edu.hhu.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class MemberDao {
    private final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    public List<Student> queryStudentsByCid(long cid) {
        String sql = "select student_info.sid, sname from student_info, course_member where cid=? and student_info.sid=course_member.sid";
        try {
            return template.query(sql, new BeanPropertyRowMapper<>(Student.class), cid);
        } catch (DataAccessException e) {
            return null;
        }
    }

    public int deleteStudentByCidAndSid(long cid, String sid) {
        String sql = "delete from course_member where cid=? and sid=?";
        try {
            return template.update(sql, cid, sid);
        } catch (DataAccessException e) {
            return 0;
        }
    }

    public int addStudentByCidAndSid(long cid, String sid) {
        String sql = "insert into course_member values (?, ?)";
        try {
            return template.update(sql, cid, sid);
        } catch (DataAccessException e) {
            return 0;
        }
    }
}
